package com.bw.educate.controller;


import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.educate.client.UserCouserClient;
import com.bw.educate.common.ResponseResult;
import com.bw.educate.common.alipay.AlipayConfig;
import com.bw.educate.entity.EduOrder;
import com.bw.educate.entity.EduPayLog;
import com.bw.educate.service.IEduOrderService;
import com.bw.educate.service.IEduPayLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 在线教育-五组
 * @since 2020-08-13
 */
@RestController
@RequestMapping("eduPayLog")
public class EduPayLogController {

    @Autowired
    private IEduPayLogService eduPayLogService;

    @Autowired
    private IEduOrderService eduOrderService;

    @Autowired
    private UserCouserClient userCouserClient;

    /**
     * @Description:订单支付日志列表
     * @Author: 周明丽
     * @Date: 2020/8/25 22:21
     * @param uid:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("list/{uid}")
    public ResponseResult addOrder(@PathVariable("uid") Long uid){
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            List<EduPayLog> list = eduPayLogService.listOrder(uid);
            result.setResult(list);
            result.setMessage("保存成功");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("订单生成失败"+e.toString());
        }
        return result;
    }

    /**
     * @Description:支付
     * @Author: 周明丽
     * @Date: 2020/8/25 22:53
     * @param eduOrder:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @PostMapping("payMoney")
    public ResponseResult payMoney(@RequestBody EduOrder eduOrder){
        ResponseResult result=ResponseResult.SUCCESS();

        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);


            alipayRequest.setBizContent("{\"out_trade_no\":\""+ eduOrder.getCode() +"\","
                    + "\"total_amount\":\""+ eduOrder.getPrice() +"\","
                    + "\"subject\":\""+ eduOrder.getCode() +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求
            String res = alipayClient.pageExecute(alipayRequest).getBody();
            result.setResult(res);
         
            
        }catch (Exception e){
			e.printStackTrace();
            result.setSuccess(false);
           
        }
        return result;
    }

    @RequestMapping("checkSign")
    public ResponseResult checkSign(HttpServletRequest request){

        ResponseResult result = ResponseResult.SUCCESS();
        try {

            //获取支付宝GET过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名


            if(!signVerified){
                //修改订单状态
                String code= request.getParameter("out_trade_no");
                BigDecimal price = new BigDecimal(params.get("total_amount"));
                //修改订单状态
                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("id",code);
                EduOrder order = eduOrderService.getOne(queryWrapper);
                order.setStatus(1);
                eduOrderService.saveOrUpdate(order);
                result.setResult(order.getCid());
                //支付日志
                EduPayLog eduPayLog = new EduPayLog();
                eduPayLog.setCode(order.getCode());
                eduPayLog.setPayMoney(order.getPrice());
                eduPayLog.setPayTime(new Date());
                eduPayLog.setSuid(order.getSuid());
                eduPayLogService.saveOrUpdate(eduPayLog);
                //远程调用进行授权
               // userCouserClient.addSave(order.getCid());

                result.setMessage("支付成功");
            }else {
                result.setMessage("支付失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            result.setMessage("支付失败");
        }

        return result;

    }

}
